package com.lwt.mvc.interceptor;

import com.lwt.constant.TongchouConstant;
import com.lwt.entity.Admin;
import com.lwt.exception.AccessForbiddenException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 登录拦截器
 * @Author Li Weitong
 * @Date 2021/1/15 16:01
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取session对象
        HttpSession session = request.getSession();
        // 从session域中获取admin对象
        Admin admin = (Admin) session.getAttribute(TongchouConstant.ATTR_NAME_LOGIN_ADMIN);
        // 判断是否登录
        if (admin == null) {
            // 未登录不允许继续访问
            throw new AccessForbiddenException(TongchouConstant.MESSAGE_ACCESS_FORBIDEN);
        }
        // 如果admin对象不为空，则放行
        return true;
    }
}
